package com.muqi.app.qlearn.student.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;

import com.muqi.app.project.utils.ShowToast;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends  Activity implements IWXAPIEventHandler {
    private static final String TAG = "WXPayEntryActivity";
    public static final String PAY_WITH_SUCCESS = "pay_with_success";
    public static final String PAY_WITH_FAILE = "pay_with_faile";
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, WePayConstants.APP_ID);
        api.handleIntent(getIntent(), this);
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    
    }

	@Override
	public void onResp(BaseResp resp) {
		Log.e("===", resp.getType()+"==");
		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			if (resp.errCode == 0) {
				ShowToast.showShort(this, "支付成功");
				paySuccess();
//				finish();
			} else if (resp.errCode == -1) {
				sendBroadcast(new Intent("payed_failed"));
				payFaile();
//				ShowToast.showShort(this, "支付失败:" + resp.errStr);
				ShowToast.showShort(this, "支付失败:");
				finish();
			} else if (resp.errCode == -2) {
				sendBroadcast(new Intent("payed_failed"));
				payFaile();
				ShowToast.showShort(this, "支付取消");
				finish();
			}
		}
	}
    
    private void paySuccess(){
    	Intent intent = new Intent();
		intent.setAction(PAY_WITH_SUCCESS);
		sendBroadcast(intent);
		finish();
	}
    private void payFaile(){
    	Intent intent = new Intent();
		intent.setAction(PAY_WITH_FAILE);
		sendBroadcast(intent);
		finish();
	}
}
